from django.shortcuts import render
from django.contrib.auth.decorators import login_required

from xadmin.models import AuditLog
from django.core.paginator import Paginator
from django.conf import settings
from django.db.models import Q


@login_required
def index(request):
    siteid = request.GET.get('siteid')
    mbx = ('管理员日志', )
    keyword = request.GET.get('keyword')
    audit_set = AuditLog.objects.filter(Q(site_id=siteid) | Q(site=None))

    if keyword:
        audit_set = audit_set.filter(Q(action__contains=keyword) | Q(user__username=keyword) | Q(user__chinese_name=keyword))

    paginator = Paginator(audit_set, settings.PAGESIZE)

    pagenum = request.GET.get('pagenum', '1')
    if not pagenum.isdigit():
        pagenum = 1
    if int(pagenum) > paginator.num_pages:
        pagenum = paginator.num_pages
    if int(pagenum) < -1:
        pagenum = 1
    audit_list = paginator.get_page(pagenum)

    context = {
        'siteid': siteid,
        'mbx': mbx,
        'keyword': keyword,
        'audit_list': audit_list,
        'paginator': paginator,
        'pagesize': settings.PAGESIZE,
        'pagenum': pagenum,
    }
    return render(request, 'xadmin/audit/list.html', context)